// ===============================================
// json_string_to_map
//
// Create by Will on 20/9/2023 02:46
// Copyright Will .All rights reserved.
// ===============================================

import 'dart:convert';

import 'package:json_annotation/json_annotation.dart';

class DynamicToMap implements JsonConverter<Map<String, dynamic>, dynamic> {
  const DynamicToMap();

  @override
  Map<String, dynamic> fromJson(dynamic json) {
    Map<String, dynamic> dataMap;
    if (json is String) {
      try {
        dataMap = jsonDecode(json) as Map<String, dynamic>;
        return dataMap;
      } catch (error) {
        // 非标准的JSON，跳过
        return {};
      }
    }

    if (json is Map<String, dynamic>) {
      return json;
    }
    return <String, dynamic>{};
  }

  @override
  Map<String, dynamic> toJson(dynamic json) {
    Map<String, dynamic> dataMap;
    if (json is String) {
      try {
        dataMap = jsonDecode(json) as Map<String, dynamic>;
        return dataMap;
      } catch (error) {
        // 非标准的JSON，跳过
        return <String, dynamic>{};
      }
    }

    if (json is Map<String, dynamic>) {
      return json;
    }
    return <String, dynamic>{};
  }
}
